package com.mtz.service.impl;

import com.mtz.dateobject.KnowledgeType;
import com.mtz.enums.ResultEnum;
import com.mtz.exception.MtzException;
import com.mtz.repository.KnowledgeTypeRepository;
import com.mtz.service.KnowledgeTypeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author 煜赜
 * @date 2018/12/17 0017 上午 9:29
 */
@Service
@Slf4j
public class KnowledgeTypeServiceImpl implements KnowledgeTypeService {

    @Autowired
    private KnowledgeTypeRepository knowledgeTypeRepository;

    @Override
    public KnowledgeType findById(Integer id) {
        if (!knowledgeTypeRepository.findById(id).isPresent()) {
            // 抛出id不存在异常
            throw new MtzException(ResultEnum.ID_NOT_EXIST);
        }
        return knowledgeTypeRepository.findById(id).get();
    }

    @Override
    public List<KnowledgeType> findAll() {
        return knowledgeTypeRepository.findAll();
    }

    @Override
    public KnowledgeType findByTypeName(String typeName) {
        KnowledgeType knowledgeType = knowledgeTypeRepository.findByTypeName(typeName);
        if (knowledgeType == null) {
            // 抛出类型不存在异常
            throw new MtzException(ResultEnum.TYPE_NOT_EXIST);
        }
        return knowledgeType;
    }

    @Override
    public void addKnowledgeType(String typeName) {
        KnowledgeType knowledgeType = new KnowledgeType();
        knowledgeType.setTypeName(typeName);
        knowledgeTypeRepository.save(knowledgeType);
    }

    @Override
    public void editKnowledgeType(Integer id, String typeName) {
        if (!knowledgeTypeRepository.findById(id).isPresent()) {
            // 抛出id不存在异常
            throw new MtzException(ResultEnum.ID_NOT_EXIST);
        }
        KnowledgeType knowledgeType = knowledgeTypeRepository.findById(id).get();
        knowledgeType.setTypeName(typeName);
        knowledgeTypeRepository.save(knowledgeType);
    }

    @Override
    public void deleteKnowledgeType(Integer id) {
        if (!knowledgeTypeRepository.findById(id).isPresent()) {
            // 抛出id不存在异常
            throw new MtzException(ResultEnum.ID_NOT_EXIST);
        }
        knowledgeTypeRepository.deleteById(id);
    }
}
